﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;


namespace advadev.CanOpen
{

    /// <summary>
    /// Represents a synchronization object write transfer
    /// </summary>
    public class SynchronizationObjectWriteTransfer : ITransfer
    {

        /// <summary>for internal use</summary>
        private bool _isProducerTransfer;
        /// <summary>for internal use</summary>
        private bool _isTransferCompleteAfterSending;
        /// <summary>for internal use</summary>
        private CanOpenMessage _receivedCanOpenMessage;
        /// <summary>for internal use</summary>
        private SynchronizationObjectReceivedEventHandler _synchronizationObjectReceivedEventHandler;
        /// <summary>for internal use</summary>
        private Collection<CanOpenMessage> _pendingSendMessages = new Collection<CanOpenMessage>();
        /// <summary>for internal use</summary>
        private ReadOnlyCollection<CanOpenMessage> _pendingSendMessagesReference;
        /// <summary>
        /// Default producer COB-ID
        /// </summary>
        static public readonly UInt16 DefaultProducerCobId = 0x080;


        /// <summary>
        /// Initializes a new instance of the SynchronizationObjectWriteTransfer
        /// class by the given parameter
        /// </summary>
        /// <param name="receivedCanOpenMessage">
        /// Received can open message
        /// </param>
        /// <param name="synchronizationObjectReceivedEventHandler">
        /// Synchronization object received event handler (or null)
        /// </param>
        private SynchronizationObjectWriteTransfer(CanOpenMessage receivedCanOpenMessage, SynchronizationObjectReceivedEventHandler synchronizationObjectReceivedEventHandler)
        {
            _isProducerTransfer = false;
            _receivedCanOpenMessage = receivedCanOpenMessage;
            _synchronizationObjectReceivedEventHandler = synchronizationObjectReceivedEventHandler;
        }

        /// <summary>
        /// Initializes a new instance of the SynchronizationObjectWriteTransfer
        /// class by the given parameter
        /// </summary>
        /// <param name="counter">
        /// Counter to send with the synchronization object (may be null)
        /// </param>
        public SynchronizationObjectWriteTransfer(byte? counter)
            : this(counter, DefaultProducerCobId)
        {
        }

        /// <summary>
        /// Initializes a new instance of the SynchronizationObjectWriteTransfer
        /// class by the given parameter
        /// </summary>
        /// <param name="counter">
        /// Counter to send with the synchronization object (may be null)
        /// </param>
        /// <param name="producerCobId">
        /// Producer COB-ID
        /// </param>
        public SynchronizationObjectWriteTransfer(byte? counter, UInt16 producerCobId)
        {
            _isProducerTransfer = true;
            ProducerCobId = producerCobId;
            Counter = counter;
        }


        /// <summary>
        /// Gets or sets the counter
        /// </summary>
        private byte? Counter
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the producer COB-ID
        /// </summary>
        private UInt16 ProducerCobId
        {
            get;
            set;
        }


        /// <summary>
        /// Checks if the given received can open message is a synchronization
        /// object write transfer request and if so it returns as out parameter
        /// a matching synchronization object write transfer instance
        /// </summary>
        /// <param name="receivedCanOpenMessage">
        /// Received can open message
        /// </param>
        /// <param name="synchronizationObjectWriteTransfer">
        /// A matching synchronization object write transfer instance
        /// </param>
        /// <param name="synchronizationObjectReceivedEventHandler">
        /// Synchronization object received event handler (or null)
        /// </param>
        /// <returns>
        /// True if the received can open message is a synchronization object
        /// write transfer request, false otherwise
        /// </returns>
        static public bool IsSynchronizationObjectWriteTransfer(CanOpenMessage receivedCanOpenMessage, out SynchronizationObjectWriteTransfer synchronizationObjectWriteTransfer, SynchronizationObjectReceivedEventHandler synchronizationObjectReceivedEventHandler)
        {
            return IsSynchronizationObjectWriteTransfer(receivedCanOpenMessage, out synchronizationObjectWriteTransfer, DefaultProducerCobId, synchronizationObjectReceivedEventHandler);
        }

        /// <summary>
        /// Checks if the given received can open message is a synchronization
        /// object write transfer request and if so it returns as out parameter
        /// a matching synchronization object write transfer instance
        /// </summary>
        /// <param name="receivedCanOpenMessage">
        /// Received can open message
        /// </param>
        /// <param name="synchronizationObjectWriteTransfer">
        /// A matching synchronization object write transfer instance
        /// </param>
        /// <param name="producerCobId">
        /// Producer COB-ID
        /// </param>
        /// <param name="synchronizationObjectReceivedEventHandler">
        /// Synchronization object received event handler (or null)
        /// </param>
        /// <returns>
        /// True if the received can open message is a synchronization object
        /// write transfer request, false otherwise
        /// </returns>
        static public bool IsSynchronizationObjectWriteTransfer(CanOpenMessage receivedCanOpenMessage, out SynchronizationObjectWriteTransfer synchronizationObjectWriteTransfer, UInt16 producerCobId, SynchronizationObjectReceivedEventHandler synchronizationObjectReceivedEventHandler)
        {
            // check parameter
            if (receivedCanOpenMessage == null)
            {
                synchronizationObjectWriteTransfer = null;
                return false;
            }

            // check COB-ID
            if (receivedCanOpenMessage.CanId != producerCobId)
            {
                synchronizationObjectWriteTransfer = null;
                return false;
            }

            // create transfer instance
            synchronizationObjectWriteTransfer = new SynchronizationObjectWriteTransfer(receivedCanOpenMessage, synchronizationObjectReceivedEventHandler);
            return true;
        }

        /// <summary>
        /// Starts the producer transfer
        /// </summary>
        private void startProducerTransfer()
        {
            UInt16 canId = ProducerCobId;
            byte byte0 = (Counter == null ? (byte)0 : Counter.Value);
            _pendingSendMessages.Add(new CanOpenMessage(canId, byte0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, (Counter == null ? (uint)0 : (uint)1)));
            _isTransferCompleteAfterSending = true;
        }

        /// <summary>
        /// Starts the consumer transfer
        /// </summary>
        private void startConsumerTransfer()
        {
            // process data
            if (_synchronizationObjectReceivedEventHandler != null && _receivedCanOpenMessage.Length > 0)
            {
                _synchronizationObjectReceivedEventHandler(this, new SynchronizationObjectReceivedEventArgs(_receivedCanOpenMessage.Byte0));
            }

            // end transfer
            TransferComplete = true;
        }


        #region ITransfer implementation
        /// <summary>
        /// Gets a flag indicating whether the transfer is complete (after
        /// sending the pending send messages)
        /// </summary>
        public bool TransferComplete
        {
            get;
            private set;
        }

        /// <summary>
        /// Gets the abort code (null for successful transfers)
        /// </summary>
        public CanOpenAbortCode AbortCode
        {
            get;
            private set;
        }

        /// <summary>
        /// Gets the pending send messages
        /// </summary>
        public ReadOnlyCollection<CanOpenMessage> PendingSendMessages
        {
            get
            {
                if (_pendingSendMessagesReference == null)
                {
                    _pendingSendMessagesReference = new ReadOnlyCollection<CanOpenMessage>(_pendingSendMessages);
                }
                return _pendingSendMessagesReference;
            }
        }


        /// <summary>
        /// Starts the transfer
        /// </summary>
        public void Start()
        {
            if (_isProducerTransfer)
            {
                startProducerTransfer();
            }
            else
            {
                startConsumerTransfer();
            }
        }

        /// <summary>
        /// Times out the transfer
        /// </summary>
        public void TimeOut()
        {
            AbortCode = new CanOpenAbortCode(0x00, 0x00, 0x04, 0x05);
        }

        /// <summary>
        /// Finalizes the transfer
        /// </summary>
        public void FinalizeTransfer()
        {
        }

        /// <summary>
        /// Continues the transfer after sending messages
        /// </summary>
        public void ContinueAfterSendingMessages()
        {
            _pendingSendMessages.Clear();
            if (_isTransferCompleteAfterSending)
            {
                TransferComplete = true;
            }
        }

        /// <summary>
        /// Processes the received message
        /// </summary>
        /// <param name="receivedCanOpenMessage">
        /// Received can open message
        /// </param>
        /// <returns>
        /// True, if the given can open message was related to this transfer,
        /// false otherwise
        /// </returns>
        public bool ProcessReceivedMessage(CanOpenMessage receivedCanOpenMessage)
        {
            return false;
        }
        #endregion ITransfer implementation

    }

}
